/**
 * Created by 功振 on 2016/2/20.
 */
angular.module("Portal").directive("ngUnique", ["userInfoService", function (userInfoService) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            element.bind('blur', function (e) {
                if (!ngModel || !element.val()) return;
                var currentValue = element.val();
                console.log("currentValue:" + currentValue);
                /*  AuthService.checkUniqueValue(keyProperty.key, keyProperty.property, currentValue)
                 .then(function (unique) {
                 //Ensure value that being checked hasn't changed
                 //since the Ajax call was made
                 if (currentValue == element.val()) {
                 console.log('unique = '+unique);
                 ngModel.$setValidity('unique', unique);
                 scope.$broadcast('show-errors-check-validity');
                 }
                 });*/
                userInfoService.isUserExisted(currentValue).then(function (response) {
                    //var isExisted = response.data;
                    var isExisted = response.data.length > 0?true:false;
                    ngModel.$setValidity('unique', !isExisted);
                    if(isExisted){
                        var _secrect = response.data[0].pullSecr;
                        //if _secrect is undefined means
                        // need to set pull secrect when user login
                        var _isSet = _secrect === undefined?true:false;
                        scope.setPullSecr = _isSet;
                    }
                    console.log("user " + currentValue + " existed:" + isExisted);
                }, function (response) {
                    console.log("Checking user " + currentValue + " exist failed");
                });

            });
        }
    }
}]);